﻿//using ARS.Control.DataPaging.Code.Attr;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ARS.Control.Custom.DataPaging.Attributes;
using ARS.Control.Custom.DataPaging.Resource;
using ARS.Control.Custom.Entity.Fields;
using ARS.Control.Factory;

namespace ARS.Control.Custom.DataPaging.Widget
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:DataPaging runat=server><AttrHtmlTable THeadTrHtml='<td></td><td></td>'><td></td><td></td></AttrHtmlTable><AttrOperat ColumnName='' IsHasOperat='false'></AttrOperat><AttrHtmlFanye IsHasFanye='false'></AttrHtmlFanye></{0}:DataPaging>")]

    public class DataPaging : WebControl
    {


        private ARS.Control.Custom.Entity.Model.EntityModel _entity;

        public ARS.Control.Custom.Entity.Model.EntityModel Entity
        {
            get { return _entity; }
            set
            {
                _entity = value;
            }
        }

        //public virtual string GetDeleteSql()
        //{
        //    return AttrDbOperat.DeleteSql;
        //}

        public const string SEARCHWHEREDELIMITER = "|&|";
       // public delegate string GetTableHtmlDelegate();

        private HtmlTable _HtmlTable;
        [Bindable(true), Category("Appearance"), Description("html相关属性"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public HtmlTable AttrHtmlTable
        {
            get
            {
                if (_HtmlTable == null)
                {
                    _HtmlTable = new HtmlTable();
                }
                return _HtmlTable;
            }
        }

        private DbSelect _DbSelect;
        [Bindable(true), Category("Appearance"), Description("sql相关属性"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public DbSelect AttrDbSelect
        {
            get
            {
                if (_DbSelect == null)
                {
                    _DbSelect = new DbSelect();
                }
                return _DbSelect;
            }
        }

        private DbOperat _DbOperat;
        [Bindable(true), Category("Appearance"), Description("操作相关属性"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public DbOperat AttrDbOperat
        {
            get
            {
                if (_DbOperat == null)
                {
                    _DbOperat = new DbOperat();
                }
                return _DbOperat;
            }
        }

        private Operat _Operat;
        [Bindable(true), Category("Appearance"), Description("和最后一列按钮相关属性"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public Operat AttrOperat
        {
            get
            {
                if (_Operat == null)
                {
                    _Operat = new Operat();
                }
                return _Operat;
            }
        }

        private Status _Status;
        [Bindable(true), Category("Appearance"), Description("运行状态"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public Status AttrStatus
        {
            get
            {
                if (_Status == null)
                {
                    _Status = new Status();
                }
                return _Status;
            }
        }

        private HtmlFanye _HtmlFanye;
        [Bindable(true), Category("Appearance"), Description("翻页相关"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public HtmlFanye AttrHtmlFanye
        {
            get
            {
                if (_HtmlFanye == null)
                {
                    _HtmlFanye = new HtmlFanye();
                }
                return _HtmlFanye;
            }
        }
        ///// <summary>
        ///// 搜索容器，遍历
        ///// </summary>
        //[Bindable(true), Category("Appearance"), Description("所搜控件关联"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        //public Panel AttrSearchPanel
        //{
        //    get;
        //    set;
        //}

        protected override void OnPreRender(EventArgs e)
        {
            //this.Page.ClientScript.RegisterClientScriptResource(typeof(DataPaging), Resource.ResoucePath.DataPaging);
            base.OnPreRender(e);
        }
        /// <summary>
        /// 输出查询语句
        /// </summary>
        public string WriteQuerySql()
        {
            string sql =
                string.Format(
                    "表名TableName:{0}，主键Key:{1}，查询字段SelectFields:{2},排序字段OrderField:{3}，查询条件StrWhere:{4},页码PageIndex:{5},每页数量PageSize:{6},联合查询条件UniteWhere:{7}",
                    AttrDbSelect.TableName, AttrDbSelect.KeyField, AttrDbSelect.SelectFields,
                    AttrDbSelect.OrderField, AttrDbSelect.StrWhere, AttrDbSelect.PageIndex, AttrDbSelect.PageSize,
                    AttrDbSelect.UniteWhere);            
            HttpContext.Current.Response.Write(sql);
            return sql;
        }

        public delegate void RenderDelegate(DataPaging dataPaging, HtmlTextWriter writer);
        /// <summary>
        /// 输出回调
        /// </summary>
        public event RenderDelegate RenderEvent;


        protected override void Render(HtmlTextWriter writer)
        {
            if (this.Visible)
            {

                this.AttrStatus.ControlId = this.ID;

                //Page.MapPath
                //string id = this.Page.MapPath;
                if (AttrStatus.ClassName == null)
                {
                    string path = this.Page.AppRelativeVirtualPath;
                    int start = path.LastIndexOf("/") + 1;
                    AttrStatus.ClassName = path.Substring(start, path.IndexOf(".aspx") - start);
                }
                //var jsName = string.Format("Dp_{0}", this.ID);
                writer.Write("<script type=\"text/javascript\">" + Res_DataPaging.DataPaging.Replace("control=DataPaging", "control=DataPaging&code=" + this.AttrStatus.ClassName).Replace("DataPaging_ID", this.ID) + "</script>");
               // writer.Write(ARS.PublicTool.WebHelper.WebPage.ScriptHelper.GetScriptStr(string.Format("var DataPaging_Operat = new DataPaging_OperatList('{0}');",this.ID)));
                //writer.Write(ARS.PublicTool.WebHelper.WebPage.ScriptHelper.GetScriptStr(string.Format("var {0} = new DataPaging_OperatList('{0}');", jsName)));

                ARS.Control.Interface.IDialog dialog = ARS.Control.Factory.DialogFactory.CreateDialog();
                this.Page.ClientScript.RegisterStartupScript(typeof(DataPaging), "dp", ARS.PublicTool.WebHelper.WebPage.ScriptHelper.GetScriptStr(string.Format("function DeleteData(id) {{ {0} }}", dialog.DataPaging_DelConfirm(this.Page, typeof(DataPaging)))));



                DataPagingDb dbModel = new DataPagingDb(this.AttrDbSelect, this.AttrHtmlTable, this.AttrOperat, this.AttrDbOperat, this.AttrStatus, this.AttrHtmlFanye);

                //获取当前用户
                Interface.IUser user = UserFactory.CreateUser();
                if (user != null)
                {
                    dbModel.Status.UserId = user.GetUserInfo().Id;
                }
                else
                {
                    dbModel.Status.UserId = -1;
                }

                List<ARS.Control.Custom.Entity.Fields.Field> fields = null;
                Func<List<ARS.Control.Custom.Entity.Fields.Field>> getLieldList = () =>
                {
                    if (fields == null)
                    {
                        fields = this.EntityTableInfo.FieldList.Where(field => field.IsListShow == true).OrderBy(
                            field => field.RankList).ToList();
                    }
                    return fields;
                };
                if (this.Entity == null)
                {
                    
                }
                else
                {
                    if (this.EntityTableInfo.KeyInfo != null)
                    {
                        this.AttrDbSelect.TableName = this.EntityTableInfo.TableName;
                        this.AttrDbSelect.KeyField = this.EntityTableInfo.KeyInfo.Key;

                        if (this.AttrDbSelect.OrderField == null)
                        {
                            this.AttrDbSelect.OrderField = this.AttrDbSelect.KeyField + " desc";
                        }
                        if (this.AttrDbSelect.SelectFields == null)
                        {
                            List<ARS.Control.Custom.Entity.Fields.Field> fieldList = getLieldList();
                            this.AttrDbSelect.SelectFields = this.AttrDbSelect.KeyField + "," + string.Join(",", from item in fieldList select item.Db_Field_Name);
                        }
                    }

                    if (string.IsNullOrEmpty(this.AttrHtmlTable.THeadTrHtml))
                    {
                        List<ARS.Control.Custom.Entity.Fields.Field> fieldList = getLieldList();
                        StringBuilder sb = new StringBuilder();
                        foreach (Field field in fieldList)
                        {
                            sb.Append(string.Format(this.GetFieldHtmlHeadText(field), field.Verbose_Name));
                        }
                        this.AttrHtmlTable.THeadTrHtml = sb.ToString();
                    }
                    if (string.IsNullOrEmpty(this.AttrHtmlTable.TBodyTrHtml))
                    {
                        List<ARS.Control.Custom.Entity.Fields.Field> fieldList = getLieldList();
                        StringBuilder sb = new StringBuilder();
                        foreach (Field field in fieldList)
                        {
                            if (field.IsUrlField)
                            {
                                sb.Append(string.Format("<td>{{{{UrlName-{0}}}}}</td>", field.Db_Field_Name));
                            }
                            else
                            {
                                sb.Append(string.Format(this.GetFieldHtmlBodyText(field), string.Format("{{{{FieldName-{0}}}}}", field.Db_Field_Name), field.CssName));

                            }
                        }
                        this.AttrHtmlTable.TBodyTrHtml = sb.ToString();
                    }

                }

                if (IsHasDiv)
                {
                    writer.Write(Factory.Dp_HtmlHelperFactory.CreateHtmlHelper().GetAllHtml(dbModel));

                }
                else
                {
                    writer.Write(Factory.Dp_HtmlHelperFactory.CreateHtmlHelper().GetAllHtmlNoDiv(dbModel));
                }

                if (this.RenderEvent != null)
                {
                    this.RenderEvent(this, writer);
                }
            }
            base.Render(writer);
        }

        public ARS.Control.Common.EntityManage.EntityTableInfo EntityTableInfo
        {
            get { return Entity.GetEntityTableInfo(); }
        }
        /// <summary>
        /// 获取和设置thead里面的内容
        /// </summary>
        public Func<Field, string> GetFieldHtmlHeadText = (field) =>
        {
            return "<td>{0}</td>";
        };
       
        /// <summary>
        /// 获取和设置tbody里面的内容
        /// </summary>
        public Func<Field,string> GetFieldHtmlBodyText= (field) =>
        {
            return "<td class='{1}'>{0}</td>";
        };


        public bool IsHasDiv = true;

        //protected override void RenderContents(HtmlTextWriter writer)
        //{
        //    if (this.Visible)
        //    {
        //        //Page.MapPath
        //        //string id = this.Page.MapPath;
        //        if (AttrStatus.ClassName == null)
        //        {
        //            string path = this.Page.AppRelativeVirtualPath;
        //            int start = path.LastIndexOf("/")+1;
        //            AttrStatus.ClassName = path.Substring(start,path.IndexOf(".aspx")-start);
        //        }
        //        writer.Write("<script type=\"text/javascript\">" + Res_DataPaging.DataPaging.Replace("control=DataPaging", "control=DataPaging&code="+this.AttrStatus.ClassName) + "</script>");

        //        ARS.Control.Interface.IDialog dialog = ARS.Control.Factory.DialogFactory.CreateDialog();
        //        this.Page.ClientScript.RegisterStartupScript(typeof(DataPaging), "dp", ARS.PublicTool.WebHelper.WebPage.ScriptHelper.GetScriptStr(string.Format("function DeleteData(id) {{ {0} }}", dialog.DataPaging_DelConfirm(this.Page, typeof(DataPaging)))));

        //        //获取当前用户
        //        Interface.IUser user = UserFactory.CreateUser();
        //        DataPagingDb dbModel = new DataPagingDb(this.AttrDbSelect, this.AttrHtmlTable, this.AttrOperat, this.AttrDbOperat, this.AttrStatus, this.AttrHtmlFanye);
        //        dbModel.Status.UserId = user.GetUserInfo().Id;

        //        writer.Write(Factory.Dp_HtmlHelperFactory.CreateHtmlHelper().GetAllHtml(dbModel));

        //        if (this.RenderEvent != null)
        //        {
        //            this.RenderEvent(this, writer);
        //        }
        //    }
        //}    
    }
}
